package com.lwl.nio.net;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

/**
 * Created by liwenlong on 2017/11/28 0:35
 */
public class ChannelAccept {

    private static final int port = 1234;
    public static final String greeting = "Hello i must be going \r\n";

    public static void main(String[] args) throws IOException, InterruptedException {
        ServerSocketChannel ssChannel = ServerSocketChannel.open();
        ServerSocket socket = ssChannel.socket();
        socket.bind(new InetSocketAddress(port));
        ssChannel.configureBlocking(false);
        ByteBuffer buffer = ByteBuffer.wrap (greeting.getBytes());
        while(true){
            System.out.println("waiting for connections");
            SocketChannel socketChannel = ssChannel.accept();
            if (socketChannel == null){
                System.out.println("2s后重新获取连接");
                Thread.sleep(20000);
            }else{
                System.out.println ("Incoming connection from: "
                        + socketChannel.socket().getRemoteSocketAddress( ));
                buffer.rewind( );
                socketChannel.write (buffer);
                socketChannel.close( );
            }
        }

    }







}
